<template>
  <main-content title="页面列表">
    <template #search-bar>
      <search-bar inline>
        <template #normal>
          <el-form-item label="输入搜索">
            <el-input v-model="searchForm.name" placeholder="页面名称" clearable />
          </el-form-item>
        </template>

        <template #toolbar>
          <el-form-item>
            <el-button type="primary" @click="onSearch">
              查询
            </el-button>
            <el-button v-has="['08020101']" type="primary" @click="goAddPage">
              新增页面
            </el-button>
          </el-form-item>
        </template>
      </search-bar>
    </template>

    <div class="toolBar">
      <el-radio-group v-model="showType">
        <el-radio-button label="list">
          列表
        </el-radio-button>
        <el-radio-button label="card">
          卡片
        </el-radio-button>
      </el-radio-group>
    </div>

    <layout-table v-if="showType === 'list'" ref="pageListTableRef" :url="listUrl" :param="searchForm">
      <el-table-column label="页面名称" prop="name" min-width="180" />
      <el-table-column label="更新时间" prop="updateTime" min-width="150">
        <template #default="scope">
          {{ formatTime(scope.row.updateTime) }}
        </template>
      </el-table-column>
      <el-table-column label="页面链接" prop="pageLink" min-width="200" />
      <el-table-column label="操作" width="130" fixed="right">
        <template #default="scope">
          <!-- <el-button link @click="_setPageHome(scope.row)">设为首页</el-button> -->
          <el-button v-has="['08020102']" link size="small" type="primary" @click="editPage(scope.row.id)">
            装修
          </el-button>
          <el-button v-has="['08020103']" link size="small" type="primary" @click="promote(scope.row)">
            预览
          </el-button>

          <el-dropdown placement="top" @command="handleCommand($event, scope.row)">
            <div style="margin-left: 10px; cursor: pointer">
              <!-- <el-icon :size="20"><More /></el-icon> -->
              <el-button v-has="['08020104', '08020105']" type="primary" link size="small">
                更多
              </el-button>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item v-has="['08020104']" command="copyPage">
                  复制
                </el-dropdown-item>
                <el-dropdown-item v-has="['08020105']" command="_deletePage">
                  删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </layout-table>

    <layout-card-list v-else ref="cardListRef" :url="listUrl" :params="searchForm">
      <template #default="{ listItem, listIndex }">
        <div class="page-card" @mouseenter="handleMouseEnter(listItem, listIndex)" @mouseleave="handleMouseLeave">
          <div v-if='listItem.homePage==1' class='home-page'>首页</div>
          <div class="img-wrapper">
            <img class="page-card-img" :src="listItem.img ?? DefaultBanner">
          </div>

          <div class="info-wrapper">
            <!-- <el-popover placement="top-start" title="名称" :width="200" trigger="hover" :content="listItem.name">
              <template #reference> -->
            <el-tooltip placement="top" :content="listItem.name" effect="light">
              <div class="name single-line">
                {{ listItem.name }}
              </div>
            </el-tooltip>
            <!-- </template>
            </el-popover> -->

            <!-- <el-popover placement="top-start" title="更新时间" :width="200" trigger="hover"
              :content="formatTime(listItem.updateTime) + '更新'">
              <template #reference> -->
            <div class="desc single-line">
              {{ formatTime(listItem.updateTime) }} 更新
            </div>
            <!-- </template>
            </el-popover> -->

            <!-- <el-popover placement="top-start" title="创建人" :width="200" trigger="hover"
              :content="listItem.createUserName + ' 创建'">
              <template #reference> -->
            <div class="desc single-line">
              {{ listItem.createUserName }} 创建
            </div>
            <!-- </template>
            </el-popover> -->
          </div>

          <div class="page-card-overlay" :class="{
            'page-card-overlay-visible': hoverIndex === listIndex
          }">
            <div class="top">
              <div v-has="['08020103']" class="preview-button" @click="promote(listItem)">
                预览
              </div>
            </div>
            <div class="bottom">
              <div v-has="['08020102']" class="button" @click="editPage(listItem.id)">
                <img class="icon" src="@/assets/pointsMall/mallPage/decorate.png" alt="装修">
                <div class="label">
                  装修
                </div>
              </div>
              <div v-has="['08020104']" class="button" @click="copyPage(listItem)">
                <img class="icon" src="@/assets/pointsMall/mallPage/copy.png" alt="复制">
                <div class="label">
                  复制
                </div>
              </div>
              <div v-has="['08020105']" class="button" @click="_deletePage(listItem)">
                <img class="icon" src="@/assets/pointsMall/mallPage/delete.png" alt="删除">
                <div class="label">
                  删除
                </div>
              </div>
            </div>
          </div>
        </div>
      </template>
    </layout-card-list>
  </main-content>
  <el-dialog v-model="dialogFormVisible" class="dialog-form" title="复制页面" width="30%" :before-close="resetForm"
    :close-on-click-modal="false">
    <el-form ref="manageForm" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="页面名称" prop="name">
        <el-input v-model="form.name" autocomplete="off" placeholder="页面名称" maxlength="30" show-word-limit />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="resetForm()">取消</el-button>
        <el-button type="primary" @click="submitForm(manageForm)">保存</el-button>
      </span>
    </template>
  </el-dialog>
  <Dialog :model-value="promoteVisible" title="扫码预览" :width="500" @close="promoteVisible = false">
    <div class="qrcode-container">
      <qrcode-vue :value="pageLink" :size="200" level="H" />
      <div class="tips">
        <div>手机扫左边二维码预览</div>
        <div>
          你也可以打开
          <a :href="pageLink" target="_blank">新窗口预览</a>
        </div>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <!-- <el-button
          v-clipboard="`${link}`"
          v-clipboard:success="clipboardSuccess"
          >复制链接</el-button
        > -->
        <el-button @click="copyItemUrl">复制链接</el-button>
        <el-button type="primary" @click="promoteVisible = false">关闭</el-button>
      </span>
    </template>
  </Dialog>
  <!-- <el-dialog class="dialog-form1" v-model="promoteVisible" title="微信扫码预览" width="30%" :close-on-click-modal="false">
    <qrcode-vue style="margin: 10px auto; display: block" :value="pageLink" :size="100" level="H" />
    <p style="margin: 10px auto; display: block; text-align: center">
      微信扫码预览
    </p>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="promoteVisible = false">关闭</el-button>
      </span>
    </template>
  </el-dialog> -->
</template>
<script lang="ts">
export default {
  name: 'DecoratePage'
}
</script>
<script setup lang="ts">
import { IMallPageData, IMallPageItem, IMallPageListRow } from "@/api/modules/pointsMall";
import { deletePage, setPageHome, getPreviewUrl, getMallPageList } from "@/api/pointsMall";
import { storePageEdit, getStorePage } from "@/api/actapp";
import LayoutTable from "@/components/table/LayoutTable.vue";
import type { FormInstance } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import QrcodeVue from "qrcode.vue";
import moment from "moment";
import { useMallConfig } from "@/views/pointsMall/compositions/useMallConfig";
import LayoutCardList from "@/components/layoutCardList/LayoutCardList.vue";
import DefaultBanner from "@/assets/app/bar/default_banner.png"

const pageLink = ref("" as any)
const router = useRouter()
const store = useStore()
const { mallConfig } = useMallConfig();
const promoteVisible = ref(false);
const pageListTableRef = ref<InstanceType<typeof LayoutTable> | null>(null)
const cardListRef = ref()
const listUrl = "/merchant/page/getPager"
const searchForm = reactive<IMallPageData>({
  relationId: store.state.pointsMall.mallConfig.id,
  insId: '',
  name: '',
})
let form = ref({
  name: "",
});
const dialogFormVisible = ref(false);
const rules = reactive({
  name: [
    {
      required: true,
      message: "请输入页面名称",
      trigger: "blur",
    },
  ],
});

const manageForm = ref<FormInstance>();

let copyItem = {
  name: "",
  pageConfig: "",
};

const resetForm = () => {
  form.value = {
    name: "",
  };
  manageForm.value?.resetFields();
  dialogFormVisible.value = false;
};

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid, fields) => {
    if (valid) {
      copyItem.name = form.value.name;
      const rs = await storePageEdit(copyItem);
      if (rs.code == 200) {
        ElMessage({
          type: "success",
          message: "复制成功",
        });
        resetForm();
        research()
      }
    } else {
      console.log("报错啦！请重试", fields);
    }
  });
};

const goAddPage = () => {
  // console.log(mallConfig.value.id)
  router.push('/mall/decorate/page/store_app/' + mallConfig.value.id + '/0')
}

const _setPageHome = async (row: IMallPageListRow) => {
  const rs = await setPageHome({ id: row.id })

  if (rs.code === 200) {
    ElMessage.success('设置成功')
    await pageListTableRef.value?.research()
  }
}

const promote = async (row: any) => {
  let rs: any = await getPreviewUrl({ id: row.id })
  if (rs.code === 200) {
    pageLink.value = rs.payload.previewUrl
    console.log('[ pageLink.value ]', pageLink.value)
    promoteVisible.value = true;
  }
};

const editPage = (id: number) => {
  router.push('/mall/decorate/page/store_app/' + store.state.pointsMall.mallConfig.id + '/' + id)
}

const _deletePage = async (row: IMallPageListRow) => {
  ElMessageBox.confirm("确认删除吗？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const rs = await deletePage({ ids: [row.id], names: [row.name] })

      if (rs.code === 200) {
        ElMessage.success('删除成功')
        research()
      }
    })
    .catch(() => {

    });
}

const copyPage = async (data: any) => {
  const rs: any = await getStorePage({ id: data.id });
  delete rs.payload.id;
  delete rs.payload.pageLink;
  copyItem = { ...rs.payload };
  dialogFormVisible.value = true;
}

const research = async () => {
  if (showType.value === "list") {
    await pageListTableRef.value?.research()
  } else {
    await cardListRef.value.research();
  }
}

const handleCommand = (command: string, row: any) => {
  if (command === "_deletePage") {
    _deletePage(row);
  } else if (command === "copyPage") {
    copyPage(row);
  }
};

const formatTime = (val: number) => {
  return moment(val).format('YYYY-MM-DD HH:mm:ss')
}

const copyItemUrl = () => {
  let oInput = document.createElement("input");
  // 将想要复制的值
  oInput.value = pageLink.value;
  // 页面底部追加输入框
  document.body.appendChild(oInput);
  // 选中输入框
  oInput.select();
  // 执行浏览器复制命令
  document.execCommand("Copy");
  // 复制后移除输入框
  ElMessage({
    showClose: true,
    message: "复制成功",
    type: "success",
  });
  oInput.remove();
};

//查询按钮查询
const onSearch = async () => {
  // await pageListTableRef.value?.research()
  research()
};

const showType = ref("card");

const hoverIndex = ref(-1);
const handleMouseEnter = (listItem: any, listIndex: number) => {
  hoverIndex.value = listIndex;
}

const handleMouseLeave = () => {
  hoverIndex.value = -1;
}

const insId = computed(() => {
  return store.state.insId.insId;
});
watch(() => insId, () => {
  searchForm.insId = insId.value
}, {
  deep: true
})

onMounted(() => {
})
</script>

<style scoped lang="scss">
.qrcode-container {
  display: flex;
  align-items: center;
  justify-content: center;

  .tips {
    color: #666666;
    margin-left: 20px;
    font-size: 14px;

    div {
      &+div {
        margin-top: 10px;
      }
    }

    a {
      color: var(--el-color-primary);
    }
  }
}

.toolBar {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px;
}

$pageCardImgHeight: 240px;

.page-card {
  width: 100%;
  height: 100%;
  box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.09);
  border-radius: 8px;
  overflow: hidden;
  position: relative;

  .img-wrapper {
    width: 100%;
    height: $pageCardImgHeight;
    background: rgba(245, 245, 245, 1);

    .page-card-img {
      object-fit: cover;
      object-position: top center;
      width: 100%;
      height: 100%;
    }
  }

  .info-wrapper {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    padding: 10px;
  }

  .single-line {
    overflow: hidden;
    text-overflow: ellipsis;
    word-break: keep-all;
    white-space: nowrap;
  }

  .name {
    color: #333;
    font-size: 16px;
    margin-bottom: 8px;
  }

  .desc {
    color: #666;
    font-size: 14px;
  }

  .desc:not(:last-child) {
    margin-bottom: 6px;
  }
}

.page-card-overlay {
  width: 100%;
  height: $pageCardImgHeight;
  display: flex;
  flex-direction: column;
  position: absolute;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.45);
  color: white;
  font-size: 14px;
  visibility: hidden;
  z-index: -1;
  opacity: 0;
  transition: opacity 200ms ease-in;

  .top {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;

    .preview-button {
      width: 130px;
      border-top: dashed 1px rgba(255, 255, 255, 1);
      border-bottom: dashed 1px rgba(255, 255, 255, 1);
      border-left: solid 1px rgba(255, 255, 255, 1);
      border-right: solid 1px rgba(255, 255, 255, 1);
      height: 36px;
      position: relative;
      border-radius: 18px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      color: #333;
      background-color: #fff;
    }

  }

  .bottom {
    height: 70px;
    display: flex;
    align-items: center;
    justify-content: space-around;

    .button {
      display: flex;
      align-items: center;
      justify-content: center;
      flex-direction: column;
      cursor: pointer;

      .icon {
        width: 30px;
        height: 30px;
        margin-bottom: 4px;
      }
    }
  }
}

.page-card-overlay-visible {
  z-index: 1;
  visibility: visible;
  opacity: 1;
}
.home-page{
  position:absolute;
  top:15px;
  left:15px;
  width:60px;
  height:30px;
  background:#333;
  color:#fff;
  line-height:30px;
  text-align:center;
  border-radius:5px;
}
</style>
